/******************************************************************************
 *
 * ngcap - network sniffer using raw sockets
 *
 * Author:        cr
 * E-mail:        cr.at.netgarage.org
 * WWW:           http://www.netgarage.org
 * Copyright (C): 2009 by cr
 *
 * This file is part of ngcap.
 *
 * ngcap is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ngcap is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ngcap.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/

#include "filter.hpp"
#include "packet_header.hpp"
#include "trace.hpp"


PacketFilter::PacketFilter(const std::string& f) : filter(f) {
    clearFilter();
    if(filter.size()>1)
        parseFilter();
}

void PacketFilter::clearFilter() {
    eth_proto=0; ip_proto=0;
    for(int i=0; i<8; ++i){
        src[i]=0;dst[i]=0;
    }
    addrf=NONE;
    sport=0;
    dport=0;
}

void PacketFilter::parseFilter() {
    parseProto();
}

void PacketFilter::parseProto() {
    Trace t("parse protocol");
    std::string::size_type loc1, loc2;
    loc1=filter.find("proto=",0);
    if(loc1==std::string::npos) return;
    loc2=filter.find(" ", loc1);
    std::string tmp=filter.substr(loc1+6,loc2-loc1+6).c_str();
    if(tmp=="arp")
        eth_proto=ETHERTYPE_ARP;
    else if(tmp=="ip")
        eth_proto=ETHERTYPE_IP;
    else if(tmp=="ipv6")
        eth_proto=ETHERTYPE_IPV6;
    else if(tmp=="tcp")
        ip_proto=IPPROTO_TCP;
    else if(tmp=="udp")
        ip_proto=IPPROTO_UDP;
    else if(tmp=="icmp")
        ip_proto=IPPROTO_ICMP;
    else return;
}

unsigned short PacketFilter::getEthProtocol() const { 
    return eth_proto; 
}


unsigned char PacketFilter::getIpProtocol() const { 
    return ip_proto; 
}

